(function() {
	
	var appModule = angular.module('tracecashModule');
	
	appModule.directive('policyHeader', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/policy/policy-header.html',
			require : '^ngModel',
			scope : {
				policy : '=ngModel',
				config : '='
			}
		};
	});
	
	appModule.directive('reinsuranceHeader', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/policy/policy-reinsurance.html',
			require : '^ngModel',
			scope : {
				reinsuranceInfo : '=ngModel'
			}
		};
	});

	appModule.directive('sinisterHeader', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/sinister/sinister-header.html',
			require : '^ngModel',
			scope : {
				sinister : '=ngModel'
			}
		};
	});

	appModule.directive('sinsiterTabs', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/sinister/sinister-tabs.html',
			require : '^ngModel',
			scope : {
				sinister : '=ngModel',
				config : '='
			}
		};
	});
	
	/**
	 * PREPARE SINISTER CONTROLLERS
	 */
	appModule.controller('NewSinisterFrontCtrl', ['$scope', '$rootScope', '$routeParams', '$http', 'configService', function($scope, $rootScope, $routeParams, $http, configService) {
		$scope.config = configService.create('', 'FRONT');
		$http.get($rootScope.REST_PATH + '/sinister/prepareFront').success(function(data) {
			$scope.message = data;
			$scope.sinister = data.payload;
		});
	}]);

	appModule.controller('NewSinisterHostCtrl', ['$scope', '$rootScope', '$routeParams', '$http', 'configService', function($scope, $rootScope, $routeParams, $http, configService) {
		$scope.config = configService.create('', 'HOST');
		$http.get($rootScope.REST_PATH + '/sinister/prepareHost', {
			params : {
				agreement : $routeParams.agreement,
				network : $routeParams.network,
				number : $routeParams.number
			}
		}).success(function(data) {
			$scope.message = data;
			$scope.sinister = data.payload;
		});
	}]);

	appModule.controller('NewSinisterPoleCtrl', ['$scope', '$rootScope', '$routeParams', '$http', 'configService', function($scope, $rootScope, $routeParams, $http, configService) {
		$scope.config = configService.create('', 'POLE');
		$http.get($rootScope.REST_PATH + '/sinister/preparePole', {
			params : {
				poleId : $routeParams.poleId
			}
		}).success(function(data) {
			$scope.message = data;
			$scope.sinister = data.payload;
		});
	}]);
	
	appModule.controller('NewSinisterCtrl', ['$scope', '$rootScope', '$routeParams', '$http', '$location', 'configService', 'sinisterService', function($scope, $rootScope, $routeParams, $http, $location, configService, sinisterService) {
		$scope.setSelectedWarranty = function(warranty) {
			$scope.sinister.warranty = warranty;
		};
		$scope.setSelectedInsured = function(insured) {
			$scope.sinister.policy.insured = insured;
		};
		$scope.prepare = function() {
			sinisterService.saveSinister($scope.sinister);
			$location.path('newSinister');
		};
	}]);
	
	/**
	 * NEW AND UPDATE SINISTER CONTROLLER
	 */
	appModule.controller('SinisterCtrl', ['$scope', '$rootScope', '$routeParams', '$http', 'configService', 'sinisterService', function($scope, $rootScope, $routeParams, $http, configService, sinisterService) {
		$("html, body").animate({ scrollTop: "0px" });
		$scope.sinister = sinisterService.getSinister();
		$scope.message = sinisterService.getMessage();
		$scope.config = configService.create($scope.sinister.state, $scope.sinister.inputType);
		$rootScope.$on('updateConfig', function () {
			$scope.config = configService.create($scope.sinister.state, $scope.sinister.inputType);
		});
		$scope.save = function() {
			var path = $rootScope.REST_PATH + '/sinister/' + ($scope.sinister.id == null ? 'persist' : 'merge');
			$scope.isLoading = true;
			$http.post(path, $scope.sinister).success(function(data) {
				$scope.message = data;
				if (data.code == $rootScope.CODE_SUCCESS) {
					$scope.sinister = data.payload;
					$scope.config = configService.create($scope.sinister.state);
				}
				$("html, body").animate({ scrollTop: "0px" });
				$scope.isLoading = false;
			}).error(function() {
				$scope.isLoading = false;
			});
		};
	}]);
	
	/**
	 * CONFIGURATION AND SINISTER SERVICES
	 */
	appModule.factory('configService', function() {
        return {
            create: function(state, type, readOnly) {
    			// Components
            	var isNew = state == null || state == '' || state == 'undefined',
	            	isReinsurance = type == 'FRONT' || type == 'POLE',
	            	isReadOnly = readOnly != null && readOnly == true,
	    			config = new Object();

    			config.reinsurance = new Object();
    			config.reinsurance.show= isReinsurance;

    			config.general = new Object();
    			config.general.disabled = !isReinsurance;
    			config.general.canChangeReserve = !isNew && !isReadOnly;
    			config.general.showReserveVariation = !isNew && !isReadOnly;
    			config.general.isNew = isNew;

    			config.policy = new Object();
    			config.policy.disabled = !isReinsurance;
    			
    			config.insured = new Object();
    			config.insured.editable = !isNew && !isReadOnly;
    			
    			config.observations = new Object();
    			config.observations.show = !isNew;
    			config.observations.editable = !isNew && !isReadOnly;
    			
    			config.documents = new Object();
    			config.documents.generateLetter = !isNew && !isReadOnly;
    			config.documents.editable = !isReadOnly;
    			
    			config.payments = new Object();
    			config.payments.show = !isNew && state != 'Comunicado' && state != 'Modificado' && state != 'Completo';
    			config.payments.editable = !isReadOnly && (state == 'Aceptado' || state == 'LiquidacionParcial' || state == 'LiquidacionTotal' || state == 'PagoSuplementario');
    			config.payments.showReserveVariation = !isReadOnly;
    			config.payments.generateLetter = !isReadOnly;
    			
    			// Actions
    			config.actions = new Object();
    			config.actions.show = !isNew && !isReadOnly;
    			config.actions.rejection = state == 'Comunicado' || state == 'Modificado' || state == 'Completo';
    			config.actions.liquidation = state == 'Aceptado' || state == 'LiquidacionParcial' || state == 'PagoSuplementario';
    			config.actions.reopen = state == 'Rechazado' || state == 'LiquidacionTotal' || state == 'ReservaCero' || state == 'CierreLiquidacion';
    			config.actions.modify = !isReadOnly;
    			return config;
            }
        };
    });
	
	appModule.factory('sinisterService', ['$rootScope', '$http', function($rootScope, $http) {
		var sinister = null, message = null;
        return {
            find: function(sinisterId) {
            	return $http.get($rootScope.REST_PATH + '/sinister/findById/' + sinisterId).success(function(data) {
            		sinister = data;
    			});
            },
            prepare: function(sinisterJson) {
				return $http.post($rootScope.REST_PATH + '/sinister/prepareWithWarranty/', sinisterJson).success(function(data) {
					sinister = data.payload;
            		message = data;
    			});
            },
            saveSinister: function(data) {
            	sinister = data;
            },
            getSinister: function() {
            	return sinister;
            },
            getMessage: function() {
            	return message;
            }
        };
    }]);

	/**
	 * HISTORY
	 */
	appModule.controller('SinisterHistoryListCtrl', ['$scope', '$rootScope', '$routeParams', '$http', function($scope, $rootScope, $routeParams, $http) {
		$scope.searchResults = {};
		$scope.sinisterId = $routeParams.sinisterId;
		$scope.setPage  = function(page) {
			$scope.currentPage = page;
			$http.get($rootScope.REST_PATH + '/history/list/' + $routeParams.sinisterId, {
				params : {
					p : $scope.currentPage,
					n : $rootScope.PAGE_SIZE
				}
			}).success(function(data) {
				$scope.searchResults = data;
			});
		};
		$scope.setPage(1);
	}]);
	
	appModule.controller('SinisterHistoryDetailCtrl', ['$scope', '$rootScope', '$routeParams', '$http', 'configService', function($scope, $rootScope, $routeParams, $http, configService) {
		$http.get($rootScope.REST_PATH + '/history/findById/' + $routeParams.historyEntityId, {}).success(function(data) {
			$scope.sinister = data;
			$scope.config = configService.create($scope.sinister.state, $scope.sinister.inputType, true);
		});
	}]);

})();